package com.zhiqian.community.controller;

import com.aliyun.oss.OSS;
import com.zhiqian.community.entity.User;
import com.zhiqian.community.service.FollowService;
import com.zhiqian.community.service.LikeService;
import com.zhiqian.community.service.UserService;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.CommunityUtil;
import com.zhiqian.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private OSS ossClient;

    @Value("${header-bucket}")
    private String headerBucket;
    @Value("${community-header-endpoint}")
    private String headerEndpoint;
    /**
     * 跳转到设置页面
     *
     * @return
     */
    @GetMapping("/setting")
    public String getSettingPage() {
        return "site/setting";
    }

    /**
     * 上传头像到OSS：头像修改功能
     *
     * @param headerImage
     * @param model
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            return CommunityUtil.getJSONString(1,"你还没有选择图片");
        }
        String filename = headerImage.getOriginalFilename();
        //获取文件后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            return CommunityUtil.getJSONString(1,"文件格式不正确");
        }
        //生成随机文件名
        filename = CommunityUtil.generateUUID() + suffix;
        try {
            //将当前文件上传到阿里云OSS
            ossClient.putObject(headerBucket,filename,new ByteArrayInputStream(headerImage.getBytes()));
        } catch (IOException e) {
            logger.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器异常");
        }
        String headerUrl = "https://"+headerEndpoint + "/" + filename;
        User user = hostHolder.getUser();
        userService.updateHeader(user.getId(), headerUrl);
        userService.setLoginUser(user.getId());
        return CommunityUtil.getJSONString(0,"头像上传成功!");
    }



    /**
     * 获取头像
     *
     * @param filename
     * @param response
     */
//    @GetMapping("/header/{filename}")
//    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response) {
//        filename = uploadPath + "/" + filename;
//        String suffix = filename.substring(filename.lastIndexOf("."));
//        response.setContentType("image/" + suffix);
//        try (FileInputStream fileInputStream = new FileInputStream(filename);
//             ServletOutputStream outputStream = response.getOutputStream();
//        ) {
//            byte[] buffer = new byte[1024];
//            int b = 0;
//            while ((b = fileInputStream.read(buffer)) != -1) {
//
//                outputStream.write(buffer, 0, b);
//            }
//        } catch (IOException e) {
//            logger.error("读取头像失败：" + e.getMessage());
//        }
//    }

    /**
     * 修改密码
     * @param password
     * @param newPassword
     * @return
     */
    @PostMapping("/updatePwd")
    @ResponseBody
    public String updatePassword(String password, String newPassword) {
        Map<String, Object> map = userService.updatePassword(password, newPassword, hostHolder.getUser());
        if (map.isEmpty()){
            return CommunityUtil.getJSONString(0,"修改成功！");
        }
        return CommunityUtil.getJSONString(1,map.get("errMsg").toString());
    }

    @GetMapping("/profile/{userId}")
    public String getProfile(@PathVariable("userId")Integer userId,Model model){
        User target = userService.getUserById(userId);
        User loginUser = hostHolder.getUser();
        if (target==null){
            throw new RuntimeException("该用户不存在");
        }
        int likeCount = likeService.selectUserHaveLikeCount(userId);
        if (!userId.equals(loginUser.getId())){
            int followStatus = followService.selectFollowStatus(ENTITY_TYPE_USER, userId, loginUser.getId());
            model.addAttribute("followStatus",followStatus);
        }
        model.addAttribute("followeeCount",followService.selectFolloweeCount(ENTITY_TYPE_USER,userId));
        model.addAttribute("followerCount",followService.selectFollowerCount(ENTITY_TYPE_USER,userId));
        model.addAttribute("target",target);
        model.addAttribute("likeCount",likeCount);
        return "/site/profile";
    }
}
